package com.sunny.design.singleton.container;

import com.google.common.collect.Maps;

import java.util.Map;

/**
 * 容器式单例
 *
 * @author Sunny
 * @date 2019/12/29 16:49
 */
public class ContainerSingleton {
    private ContainerSingleton() {
    }

    private static final Map<String, Object> ioc = Maps.newConcurrentMap();

    /**
     * 通过容器来保存实例,确保容器中的实例是唯一的
     * 容器式写法适用于创建实例非常多的情况，便于管理
     *
     * @param beanName 类全限定名
     */
    public static Object getBean(String beanName) {
        try {
            if (!ioc.containsKey(beanName)) {
                synchronized (ioc) {
                    if (!ioc.containsKey(beanName)) {
                        Object object = Class.forName(beanName).newInstance();
                        //不存在才会存入
                        ioc.putIfAbsent(beanName, object);
                        return object;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ioc.get(beanName);
    }
}
